<template>
	<div class="app-container">
		<el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true"
			v-show="showSearch" label-width="68px">
			<el-form-item label="类型" prop="type">
				<el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
					<el-option v-for="dict in dict.type.question_type" :key="dict.value" :label="dict.label"
						:value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="试卷ID" prop="paperid">
				<el-input v-model="queryParams.paperid" placeholder="请输入试卷ID" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="试卷题号" prop="idinpaper">
				<el-input v-model="queryParams.idinpaper" placeholder="请输入试卷题号" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['business:question:add']">新增
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
					v-hasPermi="['business:question:edit']">修改
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
					@click="handleDelete" v-hasPermi="['business:question:remove']">删除
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['business:question:export']">导出
				</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="题号" align="center" prop="id" />
			<el-table-column label="类型" align="center" prop="type">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.question_type" :value="scope.row.type" />
				</template>
			</el-table-column>
			<el-table-column label="试卷ID" align="center" prop="paperid" />
			<el-table-column label="试卷标题" align="center">
				<template slot-scope="scope">
					{{ getPaperTitle(scope.row.paperid) }}
				</template>
			</el-table-column>
			<el-table-column label="试卷题号" align="center" prop="idinpaper" />
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
						v-hasPermi="['business:question:edit']">修改
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['business:question:remove']">删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<!-- 添加或修改题库管理对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="题干">
					<editor v-model="form.content" :min-height="192" />
				</el-form-item>
				<el-form-item label="A">
					<editor v-model="form.a" :min-height="192" />
				</el-form-item>
				<el-form-item label="B">
					<editor v-model="form.b" :min-height="192" />
				</el-form-item>
				<el-form-item label="C">
					<editor v-model="form.c" :min-height="192" />
				</el-form-item>
				<el-form-item label="D">
					<editor v-model="form.d" :min-height="192" />
				</el-form-item>
				<el-form-item label="答案" prop="answer">
            <el-radio-group v-model="form.answer">
                <el-radio label="A">A</el-radio>
                <el-radio label="B">B</el-radio>
                <el-radio label="C">C</el-radio>
                <el-radio label="D">D</el-radio>
            </el-radio-group>
        </el-form-item>
				<el-form-item label="解析" prop="explanation">
					<editor v-model="form.explanation" :min-height="192" />
				</el-form-item>
				<el-form-item label="类型" prop="type">
					<el-radio-group v-model="form.type">
						<el-radio v-for="dict in dict.type.question_type" :key="dict.value"
							:label="dict.value">{{ dict.label }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="试卷ID" prop="paperid">
					<el-input v-model="form.paperid" placeholder="请输入试卷ID" />
				</el-form-item>
				<el-form-item label="试卷题号" prop="idinpaper">
					<el-input v-model="form.idinpaper" placeholder="请输入试卷题号" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listQuestion,
		getQuestion,
		delQuestion,
		addQuestion,
		updateQuestion
	} from "@/api/business/question";
	import {
		allPapers
	} from "@/api/business/paper";
	import {
		allUserquestionss, delUserquestions
	} from "@/api/business/userquestions";

	export default {
		name: "Question",
		dicts: ['question_type'],
		data() {
			return {
				// 存储试卷数据(新增)
				paperList: [],
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 题库管理表格数据
				questionList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					answer: null,
					type: null
				},
				// 表单参数
				form: {
    content: '',
    a: '',
    b: '',
    c: '',
    d: '',
    answer: '',
    type: '',
    explanation: '',
    paperid: '',
    idinpaper: ''
},
rules: {
    content: [
        { required: true, message: '题干不能为空', trigger: 'blur' }
    ],
    a: [
        { required: true, message: 'A不能为空', trigger: 'blur' }
    ],
    b: [
        { required: true, message: 'B不能为空', trigger: 'blur' }
    ],
    c: [
        { required: true, message: 'C不能为空', trigger: 'blur' }
    ],
    d: [
        { required: true, message: 'D不能为空', trigger: 'blur' }
    ],
    answer: [
        { required: true, message: '答案不能为空', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '类型不能为空', trigger: 'change' }
    ]
}
			};
		},
		created() {
			this.getList();
			this.getPaperList(); // 获取试卷数据
		},
		methods: {
			/** 查询题库管理列表 */
			getList() {
				this.loading = true;
				listQuestion(this.queryParams).then(response => {
					this.questionList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			/** 获取试卷列表 */
			getPaperList() {
				allPapers({}).then(response => {
					this.paperList = response.data;
				});
			},
			/** 根据 paperid 获取试卷标题 */
			getPaperTitle(paperid) {
				const paper = this.paperList.find(p => p.id === Number(paperid));
				return paper ? paper.name : '';
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					id: null,
					content: null,
					a: null,
					b: null,
					c: null,
					d: null,
					answer: null,
					type: null,
					explanation: null,
					paperid: null,
					idinpaper: null
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "添加题库管理";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const id = row.id || this.ids
				getQuestion(id).then(response => {
					this.form = response.data;
					this.open = true;
					this.title = "修改题库管理";
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						console.log('Submitting form:', this.form);
						if (this.form.id != null) {
							updateQuestion(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addQuestion(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
    const ids = row.id || this.ids;
    this.$modal.confirm('删除操作是不可逆的，是否确认删除？').then(() => {
        return allUserquestionss({ questionId: ids });  // 修改查询参数
    }).then(response => {
        
        const userQuestionIds = response.data.map(item => item.id);

        // 删除所有相关的 userquestions
        const deletePromises = userQuestionIds.map(id => {
            return delUserquestions(id);
        });

        return Promise.all(deletePromises);
    }).then(() => {
        return delQuestion(ids);
    }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
    }).catch(error => {
        console.error('删除过程中发生错误:', error);
    });
},
			/** 导出按钮操作 */
			handleExport() {
				this.download('business/question/export', {
					...this.queryParams
				}, `question_${new Date().getTime()}.xlsx`)
			}
		}
	};
</script>